﻿using Microsoft.AspNetCore.Mvc;
using RedDockNet_BackEnd.Model;
using RedDockNet_BackEnd.Service;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RedDockNet_BackEnd.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly UserService service;

        public UserController(UserService service)
        {
            this.service = service;
        }

        [HttpGet]
        public IActionResult Select()
        {
            return this.Ok(this.service.Select());
        }

        [HttpGet]
        [Route("{id:length(24)}")]
        public IActionResult Select(string id)
        {
            IActionResult result;
            User user = this.service.Select(id);
            if (user == null)
            {
                result = this.NotFound();
            }
            else
            {
                result = this.Ok(user);
            }
            return result;
        }

        [HttpPost]
        public IActionResult Insert(User user)
        {
            // 逻辑删除标志需为false
            user.Deleted = false;
            this.service.Insert(user);
            return this.Ok();
        }

        [HttpPost]
        public IActionResult Update(User user)
        {
            IActionResult result;
            user = this.service.Select(user.ObjectId);
            if (user == null)
            {
                result = this.NotFound();
            }
            else
            {
                // 逻辑删除标志需为false
                user.Deleted = false;
                this.service.Update(user);
                result = this.Ok();
            }
            return result;
        }

        [HttpPost("{id:length(24)}")]
        public IActionResult Delete(string id, bool logically = true)
        {
            IActionResult result;
            User user = this.service.Select(id);
            if (user == null)
            {
                result = this.NotFound();
            }
            else
            {
                // 逻辑删除
                if (logically)
                {
                    user.Deleted = true;
                    this.service.Update(user);
                }
                // 物理删除
                else
                {
                    this.service.Delete(id);
                }
                result = this.Ok();
            }
            return result;
        }
    }
}
